﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ViewModel;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace IssueTracker.CustomControls
{
    public partial class stickyForm_Statistics : UserControl
    {
        //PopUp notify = null;

        public StickyForm objStickyForm;
        int currentNewIssue = 0;
        public stickyForm_Statistics()
        {
            InitializeComponent();
        }

        #region background worker

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string announcerIP = e.Argument.ToString();
            while (ActiveSession.User.ID > 0)
            {
                // Data buffer for incoming data.
                byte[] bytes = new byte[1024];

                // Connect to a remote device.
                try
                {
                    // Establish the remote endpoint for the socket.
                    // This example uses port 11000 on the local computer.
                    //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                    //IPAddress ipAddress = ipHostInfo.AddressList[0];

                    IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(ActiveSession.AnnouncerIP), ActiveSession.Port);

                    // Create a TCP/IP  socket.
                    Socket receiver = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);

                    // Connect the socket to the remote endpoint. Catch any errors.
                    try
                    {
                        // Receive the response from the remote device.
                        while (true)
                        {
                            receiver.Connect(remoteEP);
                            int bytesRec = receiver.Receive(bytes);
                            string str = Encoding.ASCII.GetString(bytes, 0, bytesRec);
                            if (!string.IsNullOrEmpty(str))
                                backgroundWorker1.ReportProgress(0, str);
                        }
                    }
                    catch (ArgumentNullException ane)
                    {

                    }
                    catch (SocketException se)
                    {

                    }
                    catch (Exception e1)
                    {

                    }
                    finally
                    {
                        Thread.Sleep(5 * 1000);
                    }

                }
                catch (Exception e2)
                {

                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            lblNewIssues.Text = String.Format("{0}", Service.Sticky.GetCount(Status.New));
            lblOpen.Text = String.Format("{0}", Service.Sticky.GetCount(Status.Open));
            lblInProgress.Text = String.Format("{0}", Service.Sticky.GetCount(Status.InProgress));
            lblClosed.Text = String.Format("{0}", Service.Sticky.GetCount(Status.Closed));
            lblRejected.Text = String.Format("{0}", Service.Sticky.GetCount(Status.Rejected));
            if (ActiveSession.User.Role != Role.Admininstrator)
                NotifyToScreen(e.UserState.ToString());

        }
        #endregion

        private void ShowNewlyAssignedIssueNotification(int count)
        {
            PopUp notify = new PopUp();
            notify.panelBody.Controls.Clear();
            List<Issue> items = Service.Sticky.GetNewlyAssignedIssues(count);
            if (items.Count > 1)
            {
                popup_IssueListTemplate obj = new popup_IssueListTemplate(items);
                obj.Dock = DockStyle.Fill;
                notify.panelBody.Controls.Add(obj);
            }
            else
            {
                popup_NewIssueTemplate obj = new popup_NewIssueTemplate(items.First());
                obj.Dock = DockStyle.Fill;
                notify.panelBody.Controls.Add(obj);
            }
            notify.Show(objStickyForm);
        }

        private void NotifyToScreen(string issueIds)
        {
            PopUp notify = new PopUp();
            notify.panelBody.Controls.Clear();

            string[] _ids = issueIds.Split('|');
            List<int> ids = _ids.Select(x => Convert.ToInt32(x)).ToList();
            List<Issue> items = Service.Sticky.GetNewlyAssignedIssues(ids);
            if (ids.Count > 1)
            {
                popup_IssueListTemplate obj = new popup_IssueListTemplate(items);
                obj.Dock = DockStyle.Fill;
                notify.panelBody.Controls.Add(obj);
            }
            else
            {
                popup_NewIssueTemplate obj = new popup_NewIssueTemplate(items.First());
                obj.Dock = DockStyle.Fill;
                notify.panelBody.Controls.Add(obj);
            }

            notify.Show();
        }

        private void stickyForm_Statistics_Load(object sender, EventArgs e)
        {
            lblNewIssues.Text = String.Format("{0}", Service.Sticky.GetCount(Status.New));
            lblOpen.Text = String.Format("{0}", Service.Sticky.GetCount(Status.Open));
            lblInProgress.Text = String.Format("{0}", Service.Sticky.GetCount(Status.InProgress));
            lblClosed.Text = String.Format("{0}", Service.Sticky.GetCount(Status.Closed));
            lblRejected.Text = String.Format("{0}", Service.Sticky.GetCount(Status.Rejected));

            this.backgroundWorker1.RunWorkerAsync(ActiveSession.AnnouncerIP);

        }

        private void btnViewDetails_Click(object sender, EventArgs e)
        {
            objStickyForm.ShowMainWindow();
        }

        private void stickyForm_Statistics_MouseHover(object sender, EventArgs e)
        {
            lnkViewDetails.Visible = true;
        }

        public void StopPendingBackgroundOperation()
        {
            if (this.backgroundWorker1.IsBusy)
                this.backgroundWorker1.CancelAsync();
        }
    }
}
